import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { UserInfo } from '@/type/UserType';
import { fetchUserInfoAPI } from '@/API/userAPI';
import { AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';

type InitialState = {
  userInfo: UserInfo
}

const initialState: InitialState = {
  userInfo: {} as UserInfo,
};


/**
 * @description 获取用户信息的异步函数
 * */
export const fetchUserInfo: AsyncThunk<UserInfo, void, AsyncThunkConfig> = createAsyncThunk('fetchUserInfo', async (_, { rejectWithValue }) => {
  try {
    const { data } = await fetchUserInfoAPI();
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

const userStore = createSlice({
  name: 'userStore',
  initialState,
  reducers: {},
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(fetchUserInfo.fulfilled, (state: InitialState, action: PayloadAction<UserInfo>) => {
      const { payload } = action;
      state.userInfo = payload;
    });
  },
});


export default userStore.reducer;